package com.db.chat.server;

import com.db.chat.logging.AbstractLogger;
import com.db.chat.logging.ConsoleLogger;
import com.db.chat.server.history.HistoryException;
import com.db.chat.server.history.HistoryHandler;

import java.io.IOException;
import java.net.ServerSocket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by Student on 25.11.2014.
 */
public class Server {
    private static final int DEFAULT_PORT = 10002;
    private static final String DEFAULT_HISTORY_PATH = "./history.txt";
    private static final int MAX_CLIENTS = 1000;

    public static void main(String[] args) {
        int port = args.length > 0? Integer.parseInt(args[0]) : DEFAULT_PORT;
        startServer(port);
    }

    public static void startServer(int port) {
        AbstractLogger logger = new ConsoleLogger();
        logger.write("Server started with port "+port);

        try (ServerSocket serverSocket = new ServerSocket(port)){

            HistoryHandler hHandler = new HistoryHandler(DEFAULT_HISTORY_PATH);
            //Initiate and start broadcaster;
            ControllerThread broadcaster = new ControllerThread(hHandler, logger);

            new Thread(broadcaster).start();

            ExecutorService executor = Executors.newFixedThreadPool(MAX_CLIENTS);
            int clientIndex = 1;
            while (true) {
                try {
                    Transport transport = new Transport(serverSocket.accept());
                    logger.write("Client connected, creating worker thread");
                    WorkerThread worker = new WorkerThread(hHandler, logger, transport, broadcaster, "guest" + clientIndex++);
                    executor.submit(worker);
                } catch (IOException e) {
                    logger.write(e.getMessage());
                }
            }
        } catch (IOException e) {
            logger.write("Failed to start server due to exception "+ e);
        } catch (HistoryException e) {
            logger.write("History is not written");
        }
    }
}

